import { Hono } from 'hono';
import { TestDatabase } from './testDb';
import { createTestAuthRoutes } from './testAuthRoutes';

export class TestServer {
  private app: Hono;
  private testDb: TestDatabase;

  constructor() {
    this.app = new Hono();
    this.testDb = TestDatabase.getInstance();
  }

  private async setupRoutes() {
    const dataSource = await this.testDb.connect();

    // 添加测试认证路由
    const testAuthRoutes = createTestAuthRoutes(dataSource);
    this.app.route('/auth', testAuthRoutes);

    // 添加健康检查路由
    this.app.get('/health', (c) => {
      return c.json({ status: 'ok', timestamp: new Date().toISOString() });
    });
  }

  async initialize() {
    await this.testDb.connect();
    await this.setupRoutes();
  }

  async cleanup() {
    await this.testDb.clearDatabase();
  }

  async shutdown() {
    await this.testDb.disconnect();
  }

  getApp() {
    return this.app;
  }

  // 辅助方法：创建请求
  async request(method: string, path: string, options: {
    body?: any;
    headers?: Record<string, string>;
  } = {}) {
    const { body, headers = {} } = options;
    
    // 设置默认headers
    const defaultHeaders = {
      'Content-Type': 'application/json',
      ...headers
    };

    const req = new Request(`http://localhost${path}`, {
      method: method.toUpperCase(),
      headers: defaultHeaders,
      body: body ? JSON.stringify(body) : undefined,
    });

    return await this.app.request(req);
  }

  // 便捷方法
  async get(path: string, headers?: Record<string, string>) {
    return this.request('GET', path, { headers });
  }

  async post(path: string, body?: any, headers?: Record<string, string>) {
    return this.request('POST', path, { body, headers });
  }

  async put(path: string, body?: any, headers?: Record<string, string>) {
    return this.request('PUT', path, { body, headers });
  }

  async delete(path: string, headers?: Record<string, string>) {
    return this.request('DELETE', path, { headers });
  }
}
